import XLSX from 'xlsx-js-style'
import FileSaver from 'file-saver'
import ExcelJS from 'exceljs'

import { PRODUCT_SORT } from '@/assets/js/params.js'

const columns = [
  'HK',
  'HZ',
  'HZB',
  'H-K-2-黄',
  'H1-K-2-黄',
  'H-K-4',
  'H1-K-4',
  'H2-K-4',
  'H1-Z-2',
  'H2-Z-2',
  'H-K-2',
  'H1-K-2',
  'H2-K-2',
  'HKT',
  'H1-Z-3',
  'H2-Z-3',
  'HZT-2',
  'HZT',
  'LPKK',
  'H-K-3',
  'H1-K-3',
  'H2-K-3',
  'H1-Z-1',
  'H2-Z-1',
  'H-K-1',
  'H1-K-1',
  'H2-K-1',
  'H1-Z-4',
  'H2-Z-4',
  'H-KF-1',
  'H1-KF-2',
  'H2-KF-3',
  'HG',
  'HGD',
  'H-K-5',
  'H1-K-5',
  'H2-K-5',
  'TS-1',
  'H-K-6',
  'H1-K-6',
  'H2-K-6',
  'LJT',
  'DZ',
  'NNDZ',
  'DP-4',
  'DP-3',
  'DP-2',
  'DP-1',
  'S-Z-单',
  'S-Z-双',
  'SZB-左',
  'SZB-右',
  'SZB-中',
  'S-K-左',
  'S-K-右',
  'S-K-中',
  'S-K-13',
  'S2-K-10',
  'S-K-1',
  'S-K-2',
  'S-K-3',
  'S-K-4',
  'S-K-5',
  'S-Z-2',
  'S-K-6',
  'S2-K-1',
  'S2-K-2',
  'S2-K-3',
  'S2-K-4',
  'S2-Z-1',
  'S2-K-5',
  'S2-K-6',
  'S-K-9',
  'S2-K-9',
  'S-K-10',
  'SZ-4',
  'S-K-12',
  'ZJ',
  'SZ-3',
  'S-K-11',
  'S-K-12',
  'S-K-8',
  'S2-K-8',
  'DK-1',
  'DK-2',
  'XK-1',
  'XK-2',
  'HZ-DP',
  'S-K-14',
  'S2-K-13',
  'M8-50',
  'M8',
  'M8-20',
  'M4-16',
  'TS-2',
  'GL',
  'S-DT-1',
  'S2-DT-2',
  'DT-1',
  'DT-2',
  'DT-3',
  'DT-4',
  'DT-5',
  'DT-6',
  'SYD',
  'ZYTC',
  'XXTC',
  'SCTC',
  'PBTC',
  'CKDB',
  'QCJ-1',
  'QCJ-1.5',
  'QCJ-2',
  'QCJ-4',
  'QCJ-6',
  'QCJ-3',
  'QCJ-5',
  'QCJ-7',
  'ZCJ-1',
  'ZCJ-2',
  'ZCJ-4',
  'ZCJ-5',
  'ZCJ-3',
]
function s2ab(s) {
  var buf = new ArrayBuffer(s.length)
  var view = new Uint8Array(buf)
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
  return buf
}
const quinn = {
  downloadSale(params) {
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet('Sheet1')
    worksheet.mergeCells('A1:H1')
    worksheet.getCell('H1').value = '销售单'
    worksheet.getCell('H1').font = { size: 14, bold: true }
    worksheet.getCell('H1').alignment = {
      horizontal: 'center',
      vertical: 'center',
    }
    worksheet.mergeCells('A2:B2')
    worksheet.mergeCells('C2:D2')
    worksheet.getCell('B2').value = '出仓仓库'
    worksheet.getCell('D2').value = params['出仓仓库']
    worksheet.getCell('E2').value = '日期'
    worksheet.mergeCells('F2:H2')
    worksheet.mergeCells('A3:B3')
    worksheet.getCell('B3').value = '门店名称'
    worksheet.mergeCells('A4:B4')
    worksheet.getCell('B4').value = '门店位置'
    worksheet.mergeCells('A5:B5')
    worksheet.getCell('B5').value = '门店联系人'
    worksheet.mergeCells('A6:B6')
    worksheet.getCell('B6').value = '仓库联系人'
    console.log(params['仓库联系人'])
    worksheet.mergeCells('C3:H3')
    worksheet.mergeCells('C4:H4')
    worksheet.mergeCells('C5:H5')
    worksheet.mergeCells('C6:H6')

    worksheet.getCell('H6').value = params['仓库联系人']
    worksheet.getCell('H5').value = params['门店联系人']
    worksheet.getCell('H4').value = params['门店位置']
    worksheet.getCell('H3').value = params['门店名称']
    worksheet.getCell('H2').value = params['日期']

    const columns = [
      '序号',
      '材料名称',
      '规格',
      '色号',
      '数量',
      '单位',
      '销售价格',
      '金额',
    ]
    ;['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'].forEach((char, idx) => {
      worksheet.getCell(`${char}7`).value = columns[idx]
    })

    worksheet.insertRows(8, params.list)
    ;['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'].forEach((char) => {
      for (let i = 0, len = 7 + params.list.length; i < len; i++) {
        worksheet.getCell(`${char}${i + 1}`).border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' },
        }
      }
    })
    const len = 7 + params.list.length
    worksheet.mergeCells(`A${len}:G${len}`)

    worksheet.getCell(`H${len}`).value = params['合计']
    worksheet.getCell(`G${len}`).alignment = {
      horizontal: 'center',
      vertical: 'center',
    }
    workbook.xlsx.writeBuffer().then((buffer) => {
      let _file = new Blob([buffer], {
        type: 'application/octet-stream',
      })
      saveAs(_file, `${params?.excelName || '销售单'}.xlsx`)
    })
  },
  downloadProcure(params) {
    console.log(params)
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet('Sheet1')
    worksheet.mergeCells('A1:H1')
    worksheet.getCell('H1').value = '材料采购单'
    worksheet.getCell('H1').font = { size: 14, bold: true }
    worksheet.getCell('H1').alignment = {
      horizontal: 'center',
      vertical: 'center',
    }
    const configs = [
      ['仓库', '采购代码'],
      ['下单人', '下单日期'],
      ['预付款', '尾款'],
      ['备注', ''],
      ['仓库联系人', '仓库备用联系人'],
      ['银行账户', '银行户名'],
    ]
    configs.forEach((item, index) => {
      worksheet.getCell(`A${index + 2}`).value = item[0]
      worksheet.getCell(`F${index + 2}`).value = item[1]
      item[1] && worksheet.mergeCells(`B${index + 2}:E${index + 2}`)

      const cell1 = worksheet.getCell(`E${index + 2}`)
      cell1.value = params[item[0]]
      cell1.font = { bold: true }
      cell1.alignment = { horizontal: 'center', vertical: 'center' }
      item[1] && worksheet.mergeCells(`G${index + 2}:H${index + 2}`)
      const cell2 = worksheet.getCell(`H${index + 2}`)
      cell2.value = params[item[1]]
      cell2.font = { bold: true }
      cell2.alignment = { horizontal: 'center', vertical: 'center' }
      if (!item[1]) {
        worksheet.mergeCells(`B${index + 2}:H${index + 2}`)
        worksheet.getCell(`H${index + 2}`).value = params[item[0]]
      }
    })

    worksheet.mergeCells('A8:E8')
    worksheet.getCell('E8').value = '银行'
    worksheet.mergeCells('F8:H8')
    worksheet.getCell('H8').value = params['银行']
    worksheet.getCell('H8').alignment = {
      horizontal: 'center',
      vertical: 'center',
    }
    worksheet.getCell(`H8`).font = { bold: true }
    worksheet.getCell('E8').alignment = {
      horizontal: 'center',
      vertical: 'center',
    }

    const columns = [
      '序号',
      '名称',
      '规格',
      '色号',
      '数量',
      '单位',
      '单价',
      '金额',
    ]
    ;['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'].forEach((char, idx) => {
      worksheet.getCell(`${char}9`).value = columns[idx]
    })

    worksheet.getCell('A10').value = '下单单据'

    worksheet.getCell('A12').value = '审批栏'

    worksheet.insertRows(10, params.list)
    const position = 10 + params.list.length
    worksheet.mergeCells(`B${position}:F${position}`)
    worksheet.getCell(`F${position}`).value = '付款凭证'
    worksheet.getCell(`F${position}`).alignment = {
      horizontal: 'center',
      vertical: 'center',
    }
    worksheet.mergeCells(`G${position}:H${position}`)
    worksheet.getCell(`G${position}`).value = '到货单据'
    worksheet.getCell(`G${position}`).alignment = {
      horizontal: 'center',
      vertical: 'center',
    }
    ;['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'].forEach((char) => {
      for (let i = 0, len = 12 + params.list.length; i < len; i++) {
        worksheet.getCell(`${char}${i + 1}`).border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' },
        }
      }
    })
    const allLen = 12 + params.list.length
    worksheet.mergeCells(`B${allLen}:H${allLen}`)
    workbook.xlsx.writeBuffer().then((buffer) => {
      let _file = new Blob([buffer], {
        type: 'application/octet-stream',
      })
      FileSaver.saveAs(_file, (params.excelName || '采购单') + '.xlsx')
    })
  },
  expTable(props) {
    let {
      sort = true,
      columns = [],
      datamerges = [],
      fileName = '导出文件',
      type = 'file',
      data,
    } = props
    console.log(props)
    const headers = [columns.map((e) => e.label)]
    const keys = columns.map((e) => e.prop)
    data = data.map((e, i) => {
      const res = {}
      keys.forEach((k) => {
        try {
          res[k] = e[k]
        } catch (e) {}
      })
      res.s = {
        alignment: {
          horizontal: 'center', //水平居中
        },
      }
      return res
    })
    // return console.log(data);
    let key = ''
    const ws = XLSX.utils.book_new()
    XLSX.utils.sheet_add_aoa(ws, headers)
    XLSX.utils.sheet_add_json(ws, data, {
      origin: 'A' + (headers.length + 1),
      skipHeader: true,
    })
    let wscols = columns.map(() => ({ wch: 20 }))
    ws['!cols'] = wscols
    if (datamerges.length) ws['!merges'] = datamerges
    const wb = {
      Sheets: {
        Sheet1: ws,
      },
      SheetNames: ['Sheet1'],
    }
    var title = fileName
    const wopts = {
      bookType: 'xlsx',
      bookSST: false,
      type: 'binary',
    }
    const blob = new Blob([s2ab(XLSX.write(wb, wopts))], {
      type: 'application/octet-stream',
    })
    title = title + '.' + (wopts.bookType == 'biff2' ? 'xls' : wopts.bookType)
    if (type == 'blob') return new File([blob], title)
    FileSaver.saveAs(blob, title)
  },
  exportExcel(props) {
    let {
      sort = true,
      headers = [
        [
          '序号',
          '产品编码',
          '配件名称',
          '规格',
          '单位',
          '颜色',
          '总数量',
          '拣货签名',
        ],
      ],
      datamerges = [],
      defaultTitle = '出库单',
      type = 'file',
      productMap = window?.g_config?.productMap || {},
      productSort = window?.g_config?.productSort || [],
      productColumns = window?.g_config?.productColumns || {},
      group = true,
      data,
    } = props
    console.log(props)
    if (sort)
      data = data.sort(
        (a, b) =>
          productSort.indexOf(a.productCode) -
          productSort.indexOf(b.productCode)
      )
    data = data.map((e, i) => {
      const { productCode, productName, norms, unit, count, colour } = e
      return {
        i: i + 1,
        productCode,
        productName,
        norms,
        unit,
        colour,
        count,
        s: {
          alignment: {
            horizontal: 'center', //水平居中
          },
        },
      }
    })
    let key = ''

    if (group)
      for (let i = 0; i < data.length; i++) {
        const item = data[i]
        const k = productMap[item.productCode]
        // console.log(i, k, key, item.productCode);
        if (k != key) {
          data.splice(i, 0, {
            i: k,
            productCode: k,
            productName: k,
            norms: k,
            unit: k,
            colour: k,
            count: k,
          })
          datamerges.push({
            s: { r: i + 1, c: 0 },
            e: { r: i + 1, c: headers[0].length - 1 },
          })
          i++
          key = k
        }
      }
    console.log(data)
    // return;

    // data.unshift({
    // 	i: -1,
    // 	productCode: "productCode",
    // 	productName: "productName",
    // 	norms: "norms",
    // 	unit: "unit",
    // 	colour: "colour",
    // 	count: "count",
    // 	s: {
    // 		alignment: {
    // 			horizontal: "center", //水平居中
    // 		},
    // 	},
    // });

    const ws = XLSX.utils.book_new()
    XLSX.utils.sheet_add_aoa(ws, headers)
    XLSX.utils.sheet_add_json(ws, data, {
      origin: 'A' + (headers.length + 1),
      skipHeader: true,
    })
    let wscols = [
      { wch: 6 },
      { wch: 15 },
      { wch: 40 },
      { wch: 15 },
      { wch: 10 },
      { wch: 10 },
      { wch: 20 },
    ]
    ws['!cols'] = wscols
    ws['!merges'] = datamerges

    for (const key in ws) {
      if (
        key.indexOf('!') === -1 &&
        Object.hasOwnProperty.call(ws, key) &&
        Object.hasOwnProperty.call(ws[key], 'v')
      ) {
        ws[key].s = {
          ...(ws[key].s || {}),
          alignment: {
            horizontal: 'center',
            vertical: 'center',
            wrap_text: true,
          },
          ...(Object.keys(productColumns).includes(ws[key].v)
            ? {
                fill: {
                  fgColor: { rgb: '43CD80' },
                },
              }
            : {}),
        }
      }
    }

    const wb = {
      Sheets: {
        Sheet1: ws,
      },
      SheetNames: ['Sheet1'],
    }
    var title = defaultTitle || '列表'
    const wopts = {
      bookType: 'xlsx',
      bookSST: false,
      type: 'binary',
    }
    // return console.log(ws, wb);
    const blob = new Blob([s2ab(XLSX.write(wb, wopts))], {
      type: 'application/octet-stream',
    })
    title = title + '.' + (wopts.bookType == 'biff2' ? 'xls' : wopts.bookType)
    if (type == 'blob') return new File([blob], title)
    FileSaver.saveAs(blob, title)
  },
  setStorage(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value))
    } catch (e) {
      localStorage.setItem(key, value)
    }
  },
  getStorage(key) {
    let value = localStorage.getItem(key)
    try {
      value = JSON.parse(value)
    } catch (e) {}
    return value
  },
  removeStorage(key) {
    localStorage.removeItem(key)
  },
  clearStorage() {
    localStorage.clear()
  },
  guid(prefix = '', surfix = '') {
    const tmp = 'xxxyxxx-yxxx-'
    let res = tmp.concat(+new Date()).replace(/[xy]/g, (c) => {
      const r = (Math.random() * 16) | 0
      const v = c === 'x' ? r : (r & 0x3) | 0x8
      return v.toString(16)
    })
    return `${prefix ? prefix + '-' : ''}${res}${surfix ? '-' + surfix : ''}`
  },
  $acc: (function () {
    /**
     * floatObj 包含加减乘除四个方法，能确保浮点数运算不丢失精度
     * floatObj.add(0.1, 0.2) >> 0.3
     * floatObj.mul(19.9, 100) >> 1990
     */

    function toFixed(num, s) {
      var times = Math.pow(10, s)
      var des = num * times + 0.5
      des = parseInt(des, 10) / times
      return des
    }

    function isInteger(obj) {
      return Math.floor(obj) === obj
    }

    function toInteger(floatNum) {
      var ret = {
        times: 1,
        num: 0,
      }
      var isNegative = floatNum < 0
      if (isInteger(floatNum)) {
        ret.num = floatNum
        return ret
      }
      var strfi = floatNum + ''
      var dotPos = strfi.indexOf('.')
      var len = strfi.substr(dotPos + 1).length
      var times = Math.pow(10, len)
      var intNum = parseInt(Math.abs(floatNum) * times + 0.5, 10)
      ret.times = times
      if (isNegative) {
        intNum = -intNum
      }
      ret.num = intNum
      return ret
    }

    function operation(a, b, digits, op) {
      var o1 = toInteger(a)
      var o2 = toInteger(b)
      var n1 = o1.num
      var n2 = o2.num
      var t1 = o1.times
      var t2 = o2.times
      var max = t1 > t2 ? t1 : t2
      var result = null
      switch (op) {
        case 'add':
          if (t1 === t2) {
            // 两个小数位数相同
            result = n1 + n2
          } else if (t1 > t2) {
            // o1 小数位 大于 o2
            result = n1 + n2 * (t1 / t2)
          } else {
            // o1 小数位 小于 o2
            result = n1 * (t2 / t1) + n2
          }
          return result / max
        case 'sub':
          if (t1 === t2) {
            result = n1 - n2
          } else if (t1 > t2) {
            result = n1 - n2 * (t1 / t2)
          } else {
            result = n1 * (t2 / t1) - n2
          }
          return result / max
        case 'mul':
          result = (n1 * n2) / (t1 * t2)
          return result
        case 'div':
          result = (n1 / n2) * (t2 / t1)
          return result
      }
    }

    function add(a, b, digits) {
      return operation(a, b, digits, 'add')
    }

    function sub(a, b, digits) {
      return operation(a, b, digits, 'sub')
    }

    function mul(a, b, digits) {
      return operation(a, b, digits, 'mul')
    }

    function div(a, b, digits) {
      return operation(a, b, digits, 'div')
    }
    return {
      toFixed,
      add,
      sub,
      mul,
      div,
    }
  })(),
}
export default quinn
